package self.hoy.demo.rabbitmq.simple;

import com.rabbitmq.client.*;
import self.hoy.demo.rabbitmq.Constant;
import self.hoy.demo.rabbitmq.util.ConnectionUtils;

import javax.print.attribute.standard.QueuedJobCount;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息的消费者
 * @author hyh
 * @date 2020/6/7
 */
public class Receive implements Constant {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("new api receive : " + msg);
            }
        };
        //监听队列
        channel.basicConsume(QUEUE_NAME, true, consumer);

//        channel.close();
//        connection.close();
    }

    private static void oldApi() throws IOException, TimeoutException, InterruptedException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(QUEUE_NAME, true, consumer);

        while(true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("receive message : " + msg);
        }
    }
}
